<div id="sync">
  <h2>Sync <%= type %> <span style="color:#09f;"><%= name %></span></h2>
  <div id="sync-notify">
    <div class="ant-alert ant-alert-success">Sync started, please wait patiently.</div>
  </div>
  <h2>Log</h2>
  <pre style="min-height: 400px;" id="sync-log"></pre>
</div>
<script>
  var $log = $('#sync-log');
  var $notify = $('#sync-notify');
  var timer;
  var type = '<%= type %>';
  var name = '<%= name %>';
  if (type !== 'package') {
    name = type + ':' + name;
  }
  var resourceURL = '/sync/' + name;
  $(function() {
    var checkLogId = location.hash.match(/logid=(\d+)/);
    var logid = checkLogId ? checkLogId[1] : '';
    if (logid) {
      return getSyncLog(logid);
    }
    $.ajax({
      url: resourceURL + '?sync_upstream=true',
      type: 'PUT',
      dataType: 'json',
      success: handleSyncSucess,
      error: function (err) {
        var alert = $('<div class="ant-alert ant-alert-error"></div>');
        var message = 'Sync request error. ';
        if (err.status === 404) {
          message += name + ' not exist in official registry.';
        }
        if (err.status === 500) {
          message += 'Please refresh to sync one more time.';
        }
        $notify.html('');
        alert.html(message);
        $notify.append(alert);
      }
    });
  });
  function handleSyncSucess(data) {
    if (data.ok) {
      timer = setInterval(getSyncLog.bind(null, data.logId), 2000);
      location.hash = '#logid=' + data.logId;
      return;
    }
    $notify.html('<div class="ant-alert ant-alert-error">Sync request error.</div>');
  }

  var offset = 0;
  var logs = '';
  var syncDone = false;
  var hasFail = false;
  function getSyncLog(id) {
    $.ajax({
      url: resourceURL + '/log/' + id + '?offset=' + offset,
      type: 'GET',
      dataType: 'json',
      success: function (data) {
        if (!data.ok || !data.log) {
          return;
        }
        offset += data.log.split('\n').length;
        logs = logs + '\n' + data.log;

        if (data.log.indexOf('[done] Sync') >= 0) {
          syncDone = true;
        }
        if (data.log.indexOf('Fail: [') >= 0) {
          var failInfo = data.log.match(/Fail: \[ (.*?) \]/);
          if (failInfo && failInfo[1]) {
            hasFail = true;
          }
        }
        if (syncDone) {
          logs += '\nSync ' + name + ' complete!';
          if (hasFail) {
            logs += ' But some packages sync failed, you can refresh to sync again.';
            location.hash = '';
          }
          clearInterval(timer);
        }
        $log.html(logs);
      }
    })
  }
</script>
